<template>
  <div id="app">
    <h2>To do my list</h2>
    <el-input placeholder="请输入代办事项" v-model="newItem" style="width:40%"></el-input>
    <el-button type="primary" @click="addInfo()">添加</el-button>
    <ul>
      <li :key="value" v-for="(value,key) in items">
        {{value}}
        <div class="edit">
          <el-button size="mini" type="warning" @click="editInfo(key)">编辑</el-button>
        </div>
        <div class="delete">
          <el-button type="danger" size="mini" @click="deleteInfo(key)">删除</el-button>
        </div>
      </li>
    </ul>
    <router-view />
    <el-dialog title="编辑代办事项" :visible.sync="dialogVisible" width="30%" >
     <el-input v-model="editValue"></el-input>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="ensureEdit">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import Store from "./store.js";
export default {
  name: "app",
  data() {
    return {
      newItem: "",
      items: Store.fetch(),
      dialogVisible: false,
      editValue:'',
      currentKey:'',
    };
  },
  watch: {
    items: {
      handler(val) {
        Store.save(val);
      },
      deep: true
    }
  },
  methods: {
    ensureEdit(){
      this.$set(this.items,this.currentKey,this.editValue);
      this.$message.success('修改事项信息成功')
      this.dialogVisible = false;
      this.editValue = '';
    },
    addInfo() {
      if (this.newItem !== "") {
        this.items.push(this.newItem);
      }
      this.newItem = "";
    },
    deleteInfo(key) {
      this.items.splice(key, 1);
      this.$message.error('删除事项成功')
    },
    editInfo(key) {
      this.currentKey = key
      this.editValue = this.items[key];
      this.dialogVisible = true;
    }
  }
};
</script>

<style scoped>
ul,
li {
  list-style: none;
}
h2 {
  padding-left: 20px;
}

.delete {
  display: inline-block;
}
.edit {
  display: inline-block;
  margin-left: 150px;
}
</style>